package com.yt.generator;

import com.yt.model.MainTemplateConfig;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

/**
 * 动态生成
 */
public class DynamicGenerator {

    public static void main(String[] args) {
        String projectPath = System.getProperty("user.dir") + File.separator + "code-gen-basic";
        String inputPath = projectPath + File.separator + "src/main/resources/template/MainTemplate.java.ftl";
        String outputPath = projectPath + File.separator + "MainTemplate.java";

        MainTemplateConfig mainTemplateConfig = new MainTemplateConfig();
        mainTemplateConfig.setAuthor("YT摆渡人");
        mainTemplateConfig.setOutputText("输出结果");
        mainTemplateConfig.setLoop(true);
        try {
            doGenerate(inputPath, outputPath, mainTemplateConfig);
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        }
    }

    public static void doGenerate(String inputPath, String outputPath, Object object) throws IOException, TemplateException {
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_32);

        File file = new File(inputPath);
        configuration.setDirectoryForTemplateLoading(file.getParentFile());

        configuration.setDefaultEncoding("utf-8");
        Template template = configuration.getTemplate(file.getName());

        Writer out = new FileWriter(outputPath);
        template.process(object, out);
        out.close();
    }
}
